package com.xzc.one.common.util;

import com.alibaba.fastjson.JSON;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * 短信工具类
 *
 * @date 2018/10/26 15:02
 */
public class SmsUtil {

    public final static String DX_DEFAULT = "短信验证码:%s\n您正在使用短信验证功能,请您输入短信验证码完成验证。（短信验证，请勿泄露）";

    /**
     * 发送短信
     *
     * @param phone    手机号
     * @param template 短信模板，DX_DEFAULT
     * @param yzm      验证码
     * @return Map 响应体json格式字符串
     */
    public static Map<String, Object> getDx(String phone, String template, String yzm) {
        String url = "http://smssh1.253.com/msg/send/json";
        String account = "N3145034";//账号
        String password = "RxMJTB25tk52cd";//密码
        String msg = String.format(template, yzm);

        Map<String, Object> map = new HashMap<>();
        map.put("account", account);//创蓝 API 账号，必填
        map.put("password", password);//创蓝 API 密码，必填
        map.put("msg", msg);//：短信内容。长度不能超过 536 个字符，其中“【253 云通讯】”是签名。必填
        map.put("phone", phone);//：手机号码。多个手机号码使用英文逗号分隔，必填
        map.put("report", "true");//是否需要状态报告（默认 false），如需状态报告 则传 true，选填
        map.put("sendtime", "");//：定时发送短信时间。格式为 yyyyMMddHHmm，值 小于或等于当前时间则立即发送，默认立即发送，选填
        map.put("extend", "");//下发短信号码扩展码，纯数字，建议 1-3 位，选填
        map.put("uid", "");//该条短信在您业务系统内的 ID，如订单号或者短信发 送记录流水号，选填

        String requestJson = JSON.toJSONString(map);
        String response = sendSmsByPost(url, requestJson);
        return JSON.parseObject(response);
    }

    /**
     * Http post请求
     *
     * @param path        请求路径
     * @param postContent 请求体
     * @return String 响应体字符串
     */
    private static String sendSmsByPost(String path, String postContent) {
        URL url = null;
        try {
            url = new URL(path);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");// 提交模式
            httpURLConnection.setConnectTimeout(10000);//连接超时 单位毫秒
            httpURLConnection.setReadTimeout(10000);//读取超时 单位毫秒
            // 发送POST请求必须设置如下两行
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            httpURLConnection.setRequestProperty("Content-Type", "application/json");

//			PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
//			printWriter.write(postContent);
//			printWriter.flush();

            httpURLConnection.connect();
            OutputStream os = httpURLConnection.getOutputStream();
            os.write(postContent.getBytes("UTF-8"));
            os.flush();

            StringBuilder sb = new StringBuilder();
            int httpRspCode = httpURLConnection.getResponseCode();
            if (httpRspCode == HttpURLConnection.HTTP_OK) {
                // 开始获取数据
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(httpURLConnection.getInputStream(), "utf-8"));
                String line = null;
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
                br.close();
                return sb.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        //getDx("15979177296", DX_DEFAULT, ToolUtil.RandomUtil.getRandom(6));
        System.out.println(String.format(DX_DEFAULT, ToolUtil.RandomUtil.randomInt(6)));
    }
}
